// 配置后端

/* eslint-disable import/no-extraneous-dependencies */

import { createInterface } from 'readline';
import commandExists from 'command-exists';

import settings from '../src/lib/settings.mjs';

const commandExistsSync = commandExists.sync;
const BACKEND_EXECUTABLE_NAME = 'ANDSBackend.exe';
const GREETING = `运行这个命令之前先下载安装打包好的后端程序，下载地址为

    https://archives.tree-diagram.site/ands/ANDSBackend-with-Runtime.zip

安装完成之后找到 ${BACKEND_EXECUTABLE_NAME} 文件位置，如 C:\\Program Files\\ANDSBackend\\application\\${BACKEND_EXECUTABLE_NAME}`;

const readLine = (prompt = '') => new Promise((resolve, reject) => {
  let rl = null;
  try {
    rl = createInterface({
      input: process.stdin,
      output: process.stdout,
      terminal: false,
    });
    rl.question(prompt, (line) => {
      rl.close();
      resolve(line);
    });
  } catch (error) {
    if (rl !== null) {
      rl.close();
    }
    reject(error);
  }
});

async function confirm(prompt, yesByDefault = true) {
  while (true) {
    // eslint-disable-next-line no-await-in-loop
    const input = (await readLine(`${prompt} (${yesByDefault ? 'Y/n' : 'y/N'}) `)).trim();
    if (!input) {
      return yesByDefault;
    }
    if (input.startsWith('y') || input.startsWith('Y')) {
      return true;
    } else if (input.startsWith('n') || input.startsWith('N')) {
      return false;
    } 
    console.log('输入无效；请重新输入。');
  }
}

async function main() {
  console.log(GREETING);
  let command = null;
  if (commandExistsSync(BACKEND_EXECUTABLE_NAME)) {
    console.log(`已检测到 PATH 中含有 ${BACKEND_EXECUTABLE_NAME}，无需手动配置`);
    command = BACKEND_EXECUTABLE_NAME;
  } else {
    command = (await readLine(`输入安装后的 ${BACKEND_EXECUTABLE_NAME} 路径：`)).trim();
  }
  while (true) {
    if (commandExistsSync(command)) {
      // eslint-disable-next-line no-await-in-loop
      if (await confirm(`输入的路径为 ${command}；要继续吗？`)) {
        break;
      }
    // eslint-disable-next-line no-await-in-loop
    } else if (await confirm(`输入的路径 ${command} 似乎不正确；要继续吗？`, false)) {
      break;
    }
    // eslint-disable-next-line no-await-in-loop
    command = (await readLine(`重新输入安装后的 ${BACKEND_EXECUTABLE_NAME} 路径：`)).trim();
  }
  settings.get('backend')
    .set('command', command)
    .set('args', [])
    .write();
  console.log(`已经将配置的后端路径 ${command} 写入配置文件中。`);
}

main();
